package any.incubator;

import java.util.AbstractList;
import java.util.Collection;
import java.util.List;

public class ReverseList<E> extends AbstractList<E> {

	private final List<E> list;

	
	public static <T> List<T> reverse(List<T> list) {
		return new ReverseList<T>(list);
	}

	public ReverseList(List<E> list) throws NullPointerException {
		if (list == null) throw new NullPointerException();
		this.list = list;
	}

	@Override
	public void add(int index, E element) {
		list.add(translateIndex(index) + 1, element);
	}

	@Override
	public void clear() {
		list.clear();
	}

	@Override
	public boolean contains(Object o) {
		return list.contains(o);
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return list.containsAll(c);
	}

	@Override
	public E get(int index) {
		return list.get(translateIndex(index));
	}

	@Override
	public int indexOf(Object o) {
		return translateIndex(list.indexOf(o));
	}

	@Override
	public boolean isEmpty() {
		return list.isEmpty();
	}

	@Override
	public int lastIndexOf(Object o) {
		return translateIndex(list.lastIndexOf(o));
	}

	@Override
	public boolean remove(Object o) {
		return list.remove(o);
	}

	@Override
	public E remove(int index) {
		return list.remove(translateIndex(index));
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return list.removeAll(c);
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return list.retainAll(c);
	}

	@Override
	public E set(int index, E element) {
		return list.set(translateIndex(index), element);
	}

	@Override
	public int size() {
		return list.size();
	}

	// Helpers
	
	private int translateIndex(int index) {
		if (index < 0) {
			return index;
		} else {
			return size() - index - 1;
		}
	}
	
}
